package com.community.service.impl;


import com.aliyun.oss.OSS;
import com.community.properties.AliyunOssProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AliyunOssService {
    private final OSS ossClient;
    private final AliyunOssProperties ossProperties;

    public String upload(MultipartFile file) {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = ossProperties.getFolder() + UUID.randomUUID() + fileExt;

            // 上传到OSS
            ossClient.putObject(
                    ossProperties.getBucketName(),
                    fileName,
                    file.getInputStream()
            );

            // 返回访问URL
            return generateAccessUrl(fileName);
        } catch (Exception e) {
            throw new RuntimeException("文件上传OSS失败", e);
        }
    }

    private String generateAccessUrl(String fileName) {
        // 生成带签名的访问URL
        Date expiration = new Date(System.currentTimeMillis() + ossProperties.getExpireTime() * 1000);
        URL url = ossClient.generatePresignedUrl(
                ossProperties.getBucketName(),
                fileName,
                expiration
        );
        return url.toString();
    }

    public void delete(String fileUrl) {
        try {
            String fileName = extractFileNameFromUrl(fileUrl);
            ossClient.deleteObject(ossProperties.getBucketName(), fileName);
        } catch (Exception e) {
            throw new RuntimeException("文件删除失败", e);
        }
    }

    private String extractFileNameFromUrl(String fileUrl) {
        // 从URL中提取文件名逻辑
        return fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
    }
}